package view1.zhaolixiang.com.view1

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.View

/**
 * Created by Administrator on 2017/12/12.
 */
class MyView : View {
    //文本
    private lateinit var mTitleText:String
    //文本颜色
    private  var mTitleTextColor:Int=0
    //文本大小
    private var mTitleTextSize:Int=0
    //绘制文本打范围
    private lateinit var mBound: Rect
    private lateinit var mPaint:Paint

    constructor(context: Context) : this(context,null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs,0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
            super(context, attrs, defStyleAttr) {
        //获取我们自定的属性
        val typeArray=context.theme.obtainStyledAttributes(attrs,R.styleable.MyView,defStyleAttr,0)
        for(i in 0 until  typeArray.indexCount){
            val attr=typeArray.getIndex(i)
            when(attr){
                R.styleable.MyView_titleText->{
                    mTitleText=typeArray.getString(attr)
                }
                R.styleable.MyView_titleTextColor->{
                    mTitleTextColor=typeArray.getColor(attr, Color.BLACK)
                }
                R.styleable.MyView_titleTextSize->{
                    //默认为16sp，需要转换为px
                    mTitleTextSize=typeArray.getDimensionPixelSize(attr,
                            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,
                                    16f,resources.displayMetrics).toInt())
                }
            }
        }
        typeArray.recycle()
        //获取绘制文本的宽和高
        mPaint=Paint()
        mPaint.textSize= mTitleTextSize.toFloat()
        mBound=Rect()
        mPaint.getTextBounds(mTitleText,0,mTitleText.length,mBound)
    }

    override fun onDraw(canvas: Canvas?) {
        if (canvas != null) {
            mPaint.color=Color.YELLOW
            canvas.drawRect(0F, 0F, measuredWidth.toFloat(), measuredHeight.toFloat(),mPaint)
            mPaint.color=mTitleTextColor
            Log.i("测量measuredWidth",measuredWidth.toString())
            Log.i("测量measuredHeight",measuredHeight.toString())
            Log.i("测量width",width.toString())
            Log.i("测量height",height.toString())
            Log.i("测量mBound.width()",mBound.width().toString())
            Log.i("测量mBound.height()",mBound.height().toString())
            canvas.drawText(mTitleText, ((measuredWidth-mBound.width())/2).toFloat(),
                    ((measuredHeight+mBound.height())/2).toFloat(),mPaint)
        }

        super.onDraw(canvas)
    }
}